package com.py.custom.business.demo.core.mq.task;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.py.custom.business.demo.core.utils.MessageProcessUtils;
import com.py.custom.business.demo.feign.gateway.MessageSendGateway;
import com.py.custom.business.demo.protocol.dto.MessageTaskDTO;
import com.py.custom.business.demo.protocol.dto.SendResultDTO;
import com.py.custom.data.entity.demo.Record;
import com.py.custom.data.mapper.demo.RecordDao;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 * description：任务类，用来处理 MessageTaskDTO ；
 * 使用多例
 */
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class TaskRunDTO implements Runnable {

    private MessageTaskDTO messageTaskDto;

    @Resource
    private MessageSendGateway messageSendGateway;

    @Resource
    private RecordDao recordDao;

    public void setMessageTaskDto(MessageTaskDTO messageTaskDto) {
        this.messageTaskDto = messageTaskDto;
    }

    @Override
    public void run() {
        try {
            // 1.执行任务
            SendResultDTO resultDto = messageSendGateway.send(messageTaskDto);

            // 2.更新状态
            Integer status = MessageProcessUtils.processStatus(resultDto.getCode());
            LambdaUpdateWrapper<Record> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Record::getRecordId, messageTaskDto.getTaskId()).eq(Record::getStatus, 0)
                    .set(Objects.nonNull(status), Record::getStatus, status)
                    .set(Objects.nonNull(resultDto.getMsg()), Record::getFailMsg, resultDto.getMsg())
                    .set(Record::getUpdateTime,
                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
            recordDao.update(null, updateWrapper);
        } catch (Exception ex) {
            // 重试
        }
    }
}
